package cn.edu.cqyz.wisdom.service.impl;

import cn.edu.cqyz.wisdom.config.JwtToken;
import cn.edu.cqyz.wisdom.entity.R;
import cn.edu.cqyz.wisdom.entity.Users;
import cn.edu.cqyz.wisdom.mapper.UsersMapper;
import cn.edu.cqyz.wisdom.service.IUsersService;
import cn.edu.cqyz.wisdom.util.SampleUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * ⽤户表 服务实现类
 * </p>
 *
 * @author CDHong.it
 * @since 2024-12-18
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    public UsersMapper usersMapper;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 注册
     */
    @Override
    public R register(Users users) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", users.getUserPhone());
        if (usersMapper.selectList(wrapper).isEmpty()) {
            Users newUser = new Users();
            newUser.setUserName(users.getUserName());
            newUser.setUserPassword(users.getUserPassword());
            newUser.setUserPhone(users.getUserPhone());
            if (users.getPhoneCode().equals(valueOperations.get("registerPhone" + users.getUserPhone()))) {
                try {
                    usersMapper.insert(newUser);
                    return R.ok("注册成功!");
                } catch (Exception e) {
                    return R.error("网络异常!");
                }
            } else {
                return R.error("验证码错误！");
            }
        } else {
            return R.error("手机号已存在");
        }
    }

    /**
     * 发送注册验证码
     */
    @Override
    public R sendSmsRegister(String tel) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", tel);
        List<Users> oneUser = usersMapper.selectList(wrapper);
        if (oneUser.isEmpty()){
            // 短信模板：
            // "SMS_476800200" ： 验证码为：${code}，您正在注册MoonshotAI人工智能助手，感谢您的支持！
            // “SMS_476930165” ： 您的验证码：${code}，您正在进行身份验证，请勿泄露于他人！
            String SMS_TempId = "SMS_476800200";
            // 随机验证码
            Integer randNum = (int) (Math.random() * 10000);
            // 将验证码放入redis缓存，手机号作为 Key,过期时间 2 分钟
            try {
                redisTemplate.opsForValue().setIfAbsent("registerPhone" + tel, randNum, 2L, TimeUnit.MINUTES);
                SendSmsResponse smsResponse = SampleUtil.SendSms(tel, SMS_TempId, randNum);
                return R.data(smsResponse.body);
            } catch (Exception e) {
                return R.error("网络异常!");
            }
        }else {
            return R.error("账号存在");
        }
    }

    /**
     * 发送登录验证码
     */
    @Override
    public R sendSmsLogin(String tel) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", tel);
        List<Users> oneUser = usersMapper.selectList(wrapper);
        if (oneUser.isEmpty()) {
            return R.error("手机号未注册");
        } else {
            // 短信模板：
            // "SMS_476800200" ： 验证码为：${code}，您正在注册MoonshotAI人工智能助手，感谢您的支持！
            // “SMS_476930165” ： 您的验证码：${code}，您正在进行身份验证，请勿泄露于他人！
            String SMS_TempId = "SMS_476930165";
            // 随机验证码
            Integer randNum = (int) (Math.random() * 10000);
            try {
                // 将验证码放入redis缓存，手机号作为 Key,过期时间 2 分钟
                redisTemplate.opsForValue().setIfAbsent("registerPhone" + tel, randNum, 2L, TimeUnit.MINUTES);
                SendSmsResponse smsResponse = SampleUtil.SendSms(tel, SMS_TempId, randNum);
                return R.data(smsResponse.body);
            } catch (Exception e) {
                return R.error("网络异常!");
            }
        }
    }

    /**
     * 账号密码登录
     */
    @Override
    public R login(Users users) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", users.getUserPhone());
        if (usersMapper.selectList(wrapper).isEmpty()) {
            return R.error("此账号未注册!");
        } else {
            wrapper.eq("user_password", users.getUserPassword());
            List<Users> oneUser = usersMapper.selectList(wrapper);
            if (oneUser.isEmpty()) {
                return R.error("账号或密码错误!");
            } else {
                // 登录成功
                String token = JwtToken.createToken(oneUser.get(0));
                return R.success(token);
            }
        }
    }

    /**
     * 手机验证码登录
     */
    @Override
    public R loginCode(Users users) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", users.getUserPhone());
        List<Users> oneUser = usersMapper.selectList(wrapper);
        if (users.getPhoneCode().equals(valueOperations.get("loginPhone" + users.getUserPhone()))) {
            return R.success(JwtToken.createToken(oneUser.get(0)));
        } else {
            return R.error("验证码错误!");
        }
    }

}
